package com.joe.demo.nio.aio;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @Description
 * @Author gaojw
 * @Date 2024-08-29
 */
@Slf4j
public class FileDemo {

    public static void main(String[] args) throws IOException {
        final AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel.open(Paths.get("data.txt"), StandardOpenOption.READ);
        // 参数1 ByteBuffer
        // 参数2 读取的起始位置
        // 参数3 附件
        // 参数4 回调对象
        final ByteBuffer buffer = ByteBuffer.allocate(10);
        log.info("开始读取。。。");
        asynchronousFileChannel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {

            /**
             * read 成功
             * @param result
             * @param attachment
             */
            @Override
            public void completed(Integer result, ByteBuffer attachment) {
                log.info("read completed: {}", result);
                attachment.flip();
                log.info("读取到的数据: {}", StandardCharsets.UTF_8.decode(attachment));
            }

            /**
             * read 失败
             * @param exc
             * @param attachment
             */
            @Override
            public void failed(Throwable exc, ByteBuffer attachment) {
                log.error("读取失败");
            }
        });

        log.info("read end....");
        System.in.read();
    }
}
